package com.bawei.module_home.ui

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.library_common.route.ARouterActivityPath
import com.bawei.library_common.utils.UserUtils
import com.bawei.library_mvi.ui.BaseMviLazyFragment
import com.bawei.library_widget.event.RedPacketEnum
import com.bawei.library_widget.event.RedPacketEvent
import com.bawei.module_home.R
import com.bawei.module_home.databinding.HomeFragmentSimpleTypeBinding
import com.bawei.module_home.intent.FocusIntent
import com.bawei.module_home.intent.SimpleVideoIntent
import com.bawei.module_home.model.entity.SimpleVideoEntity
import com.bawei.module_home.state.FocusState
import com.bawei.module_home.state.SimpleVideoState
import com.bawei.module_home.ui.adapter.SimpleVideoAdapter
import com.bawei.module_home.viewmodel.FocusViewModel
import com.bawei.module_home.viewmodel.SimpleTypeViewModel
import com.bawei.module_home.viewmodel.SimpleVideoViewModel
import com.bumptech.glide.Glide
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus

//不同的分类显示不同的数据
class SimpleTypeFragment : BaseMviLazyFragment<HomeFragmentSimpleTypeBinding>() {
    private lateinit var simpleVideoModel:SimpleVideoViewModel
    private lateinit var focusViewModel: FocusViewModel
    private var channelid = ""
    private lateinit var simpleVideoAdapter:SimpleVideoAdapter
    private val list:MutableList<SimpleVideoEntity> = mutableListOf()

    override fun initView() {
        super.initView()
        initRecyclerView()
        initLoadSir()
    }

    private fun initLoadSir() {
        //设置LoadSir
        setLoadSir(viewDataBinding.rvHomeSimpleVideo)
        showLoading()
    }

    private fun initRecyclerView() {
        simpleVideoAdapter = SimpleVideoAdapter(list)
        viewDataBinding.rvHomeSimpleVideo.adapter = simpleVideoAdapter
        val layoutManager = LinearLayoutManager(requireContext())
        layoutManager.orientation = RecyclerView.VERTICAL
        viewDataBinding.rvHomeSimpleVideo.layoutManager = layoutManager

        //设置预加载
        simpleVideoAdapter.apply {
            preloadItemCount = 2
            onPreload = {
                showMsg("预加载下一页数据")
            }
        }

        //设置子控件的点击
        simpleVideoAdapter.onItemChildClick = {
            view:View,position:Int->
            when(view.id){
                //关注请求：判断用户是否登陆过
                R.id.btn_item_simple_info_subscibe ->{
                    if(UserUtils.isLogin()){
                        lifecycleScope.launch{
                            //三个参数：当前用户id  被关注用户的id position
                            val id = UserUtils.getCurrentUser()?.id //当前用户id
                            val userid = simpleVideoAdapter.getDataByPosition(position).id//被关注人的用户id 这里放视频id
                            if (id != null) {
                                focusViewModel.intents.send(FocusIntent.Focus(id.toInt(),userid.toInt(),position))
                            }
                        }
                    }else{
                        ARouter.getInstance().build(ARouterActivityPath.PAGER_LOGIN).navigation()
                    }
                }
                //点赞：不发起请求，UI切换
                R.id.iv_item_simple_info_agree ->{
                    val imageView = view as ImageView
                    if(view.tag === null || view.tag === false){
                        imageView.setImageResource(R.drawable.ic_thumb_up_check)
                        view.tag = true
                    }else{
                        imageView.setImageResource(R.drawable.ic_thumb_up)
                        view.tag = false
                    }

                }
                R.id.iv_item_simple_info_play ->{
                    ARouter.getInstance()
                        .build(ARouterActivityPath.HOMEDETAIL)
                        .withParcelable("videoData",list.get(position))
                        .navigation()
                }
            }

        }
    }


    override fun handleState() {
        lifecycleScope.launch{
            simpleVideoModel.state.collect{
                when(it){
                    is SimpleVideoState.RecommendSimpleVideo ->{//推荐视频
                        showContent()
                    }
                    is SimpleVideoState.SimpleVideoByChannelId ->{//根据通道获得
                        showSimpeVideoData(it)
                        showContent()
                    }
                    is SimpleVideoState.Empty ->{
                       showEmpty()
                    }
                    is SimpleVideoState.Error ->{
                       showFailure(it.exception.message)
                    }
                    is SimpleVideoState.Init ->{
                    }
                }
            }
        }

        lifecycleScope.launch{
            focusViewModel.states.collect{
                when(it){
                    is FocusState.FocusSuccess ->{
                        showMsg("关注成功")
                        //局部刷新
//                        simpleVideoAdapter.notifyDataSetChanged()//整个列表全部刷新
                        simpleVideoAdapter.notifyItemChanged(it.position,"focus")//只刷新当前position的item


                    }
                    is FocusState.FocusError ->{
                        showMsg("关注失败 ${it.message}")
                    }
                    is FocusState.Init ->{}
                }
            }
        }
    }

    override fun onRetryBtnClick() {
        super.onRetryBtnClick()
        lifecycleScope.launch {
            simpleVideoModel.intents.send(SimpleVideoIntent.SimpleVideoByChannelId(channelid,1,20))
        }
    }

    private fun showSimpeVideoData(it: SimpleVideoState.SimpleVideoByChannelId) {
        list.addAll(it.list)
        simpleVideoAdapter.notifyDataSetChanged()
    }

    override fun getLayout(): Int {
       return R.layout.home_fragment_simple_type
    }

    override fun initData() {
        super.initData()
        //获得不同分类channelid
        channelid = arguments?.getString("channelid").toString()
        lifecycleScope.launch {
            simpleVideoModel.intents.send(SimpleVideoIntent.SimpleVideoByChannelId(channelid,1,20))
        }
    }

    override fun generateViewModel() {
        simpleVideoModel = ViewModelProvider(this).get(SimpleVideoViewModel::class.java)
        focusViewModel = ViewModelProvider(this).get(FocusViewModel::class.java)
    }

    override fun initEvent() {
        super.initEvent()
        viewDataBinding.rvHomeSimpleVideo.addOnScrollListener(object :
            RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                simpleVideoAdapter.scrollState = newState //更新状态
                when(newState){
                    RecyclerView.SCROLL_STATE_IDLE -> {//停止滚动
                        if (rvIsScoll){
                            //滚动暂停--》恢复加载图片
                            Glide.with(requireActivity()).resumeRequests()
                        }
                        rvIsScoll=false
                        EventBus.getDefault().post(RedPacketEvent(RedPacketEnum.PAUSE))
                    }
                    RecyclerView.SCROLL_STATE_DRAGGING ->{//手指拖拽
                        rvIsScoll=true
                        //滚动----》停止加载图片
                        Glide.with(requireActivity()).pauseRequests()
                        startPlayAnim();
                    }
                    RecyclerView.SCROLL_STATE_SETTLING->{//自动滚动
                        rvIsScoll=true
                        //滚动---》停止加载图片
                        Glide.with(requireActivity()).pauseRequests()
                        startPlayAnim();
                    }
                }
            }
            })
    }





    private var  isStart  = false //是否开始动画
    private var rvIsScoll = false //是否滚动
    /**
     * 开始播放红包进度动画
     */
    private fun startPlayAnim() {
        if(isStart){
            EventBus.getDefault().post(RedPacketEvent(RedPacketEnum.RESUME))
        }else{
            EventBus.getDefault().post(RedPacketEvent(RedPacketEnum.INIT))
            isStart=true;
        }
    }


}